package accountManagementNew.service.impl;

import accountManagementNew.common.base.PersonalQueryEntity;
import accountManagementNew.common.pojo.ConsumptionRecordPersonal;
import accountManagementNew.common.vo.BlurDataVO;
import accountManagementNew.mapper.ConsumptionRecordPersonalMapper;
import accountManagementNew.service.IConsumptionRecordPersonalService;
import accountManagementNew.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 个人消费记录表 服务实现类
 *
 * @author lihonbin
 * @since 2025-09-28
 */
@Service
public class ConsumptionRecordPersonalServiceImpl extends ServiceImpl<ConsumptionRecordPersonalMapper, ConsumptionRecordPersonal> implements IConsumptionRecordPersonalService {

    @Autowired
    private ConsumptionRecordPersonalMapper consumptionRecordPersonalMapper;


    /**
     * 分页查询个人消费记录
     *
     * @param page        分页参数
     * @param queryEntity 查询参数
     * @return 分页结果
     */
    @Override
    public Page<ConsumptionRecordPersonal> queryPersonalConsumptionRecordByUsernameAndCategoryId(Page<ConsumptionRecordPersonal> page, PersonalQueryEntity queryEntity) {
        LambdaQueryWrapper<ConsumptionRecordPersonal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(queryEntity.getTypeId() != null, ConsumptionRecordPersonal::getTypeId, queryEntity.getTypeId())
                .eq(queryEntity.getUserId() != null, ConsumptionRecordPersonal::getUserId, queryEntity.getUserId());
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 查询相关消费类型的个人全部消费记录
     *
     * @param personalQuery 查询参数
     * @return 消费记录列表
     */
    @Override
    public List<ConsumptionRecordPersonal> queryAllByCategoryIdAndUserId(PersonalQueryEntity personalQuery) {
        LambdaQueryWrapper<ConsumptionRecordPersonal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(personalQuery.getTypeId() != null, ConsumptionRecordPersonal::getTypeId, personalQuery.getTypeId())
                .eq(personalQuery.getUserId() != null, ConsumptionRecordPersonal::getUserId, personalQuery.getUserId());
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 修改个人消费记录
     *
     * @param consumptionRecordPersonal 修改的消费记录
     * @return 修改结果
     */
    @Override
    @Transactional
    public boolean modifyRecord(ConsumptionRecordPersonal consumptionRecordPersonal) {
        return updateById(consumptionRecordPersonal);
    }

    /**
     * 查询所有系统预设消费类型的模糊数据
     *
     * @param id 用户id
     * @return 模糊数据
     */
    @Override
    public List<BlurDataVO> queryAllBlurDataByUserId(String id) {
        LambdaQueryWrapper<ConsumptionRecordPersonal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, ConsumptionRecordPersonal::getUserId, id);
        // 查询当前用户的全部消费记录
        List<ConsumptionRecordPersonal> consumptionRecordPersonals = baseMapper.selectList(queryWrapper);
        Map<String, List<ConsumptionRecordPersonal>> collect = new HashMap<>();
        // 根据消费类型id进行分类
        if (consumptionRecordPersonals != null && !consumptionRecordPersonals.isEmpty()){
            collect = consumptionRecordPersonals.stream().collect(Collectors.groupingBy(ConsumptionRecordPersonal::getTypeId));
        }
        // 创建返回数据
        List<BlurDataVO> blurDataVOS = new ArrayList<>();
        // 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        Map<String, LocalDateTime> dateTimeMap = DateUtils.getLastMonthFirstAndLastDay(now);
        LocalDateTime lastMonthStartTime = dateTimeMap.get(DateUtils.FIRST_DAY);
        LocalDateTime lastMonthEndTime = dateTimeMap.get(DateUtils.LAST_DAY);

        // 遍历处理返回数据
        for (Map.Entry<String, List<ConsumptionRecordPersonal>> entry : collect.entrySet()) {
            String key = entry.getKey();
            List<ConsumptionRecordPersonal> value = entry.getValue();
            BlurDataVO blurDataVO = new BlurDataVO();
            if (value != null && !value.isEmpty()){
                blurDataVO.setTypeId(key);
                BigDecimal totalAmountLast = BigDecimal.ZERO;
                BigDecimal totalAmountCurrent = BigDecimal.ZERO;
                BigDecimal totalAmountHistory = BigDecimal.ZERO;
                for (ConsumptionRecordPersonal consumptionRecordPersonal : value) {
                    LocalDateTime consumptionDate = consumptionRecordPersonal.getConsumptionDate();
                    BigDecimal amount = consumptionRecordPersonal.getAmount();
                    if (consumptionDate.isAfter(lastMonthStartTime) && consumptionDate.isBefore(lastMonthEndTime)){ // 若消费时间在上月首尾之间，则累加至上月总额。
                        totalAmountLast = totalAmountLast.add(amount);
                    }else if (consumptionDate.isAfter(now.minusMonths(1))){ // 若消费时间在上月之后，则累加到当月总额。
                        totalAmountCurrent = totalAmountCurrent.add(amount);
                    }
                    totalAmountHistory = totalAmountHistory.add(amount);
                }
                blurDataVO.setTotalAmountLast(totalAmountLast);
                blurDataVO.setTotalAmountCurrent(totalAmountCurrent);
                blurDataVO.setTotalAmountHistory(totalAmountHistory);
            }
            blurDataVOS.add(blurDataVO);
        }
        return blurDataVOS;
    }

    @Override
    @Transactional
    public boolean deletById(String id) {
        if (id != null){
            return this.removeById(id);
        }
        return false;
    }
}
